package com.youhong.teethcare.netbeans;

import android.util.Log;

import com.youhong.teethcare.utils.HttpJsonUtils2;
import com.youhong.teethcare.utils.MD5;
import com.youhong.teethcare.utils.Sha1;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2020/3/27.
 */

public class LoginServerInterface {

    public static final String ROOT_URL = "https://app.le-young.com/jcloud/usercenter";

    //   public static final String ROOT_URL="http://192.168.0.234/jcloud/usercenter";

    public static final String APP_KEY = "78d009e5e427eadd";

    public static final String SECRET = "73bcd0b57c20ba75";

    public static final String CHECK_MESSAGE = ROOT_URL + "/sms/send";

    public static final String REGISTRATION = ROOT_URL + "/user/v2/register";
    public static final String CheckCode = ROOT_URL + "/sms/verifyCode";

    public static final String LOGIN = ROOT_URL + "/user/login";

    public static final String RESET_PASSWORD = ROOT_URL + "/user/v2/retrieve";

    public static final String LOGIN_AUTH = "http://api.le-young.com/intlsso/user/loginAuth";

    public static final String CHECK_EMAIL = ROOT_URL + "/sms/sendEmail";

    public static final String HostIp = "http://api.le-young.com";

    private static NameValuePair pair_secret = new BasicNameValuePair("secret", SECRET);


    public interface LoginCallbackInterface {
        void callback(LoginHttpReturn mReturn);
    }

    public interface DefaultCallbackInterface {
        void callback(HttpReturn mReturn);
    }

    /**
     * 登录
     *
     * @param isEmailLogin
     * @param username
     * @param password
     * @param callback
     */
    public static void Login(boolean isEmailLogin, String username, String password,
                             LoginCallbackInterface callback) {
        final List<NameValuePair> params = new ArrayList<>();

        if (isEmailLogin) {

            params.add(new BasicNameValuePair("userEmail", username));

        } else {
            params.add(new BasicNameValuePair("phone", username));

        }
        params.add(new BasicNameValuePair("userpwd", MD5.getMd5_32(password)));
        String timestamp = Calendar.getInstance().getTimeInMillis() / 1000 + "";
        params.add(new BasicNameValuePair("timestamp", timestamp));
        params.add(new BasicNameValuePair("appkey", APP_KEY));
        params.add(pair_secret);



        StringableHashMap map = new StringableHashMap();
        map.addIn(params);
        String sign = Sha1.encode(map.toString());
        params.add(new BasicNameValuePair("sign", sign));
        params.remove(pair_secret);

        new Thread() {
            @Override
            public void run() {
                LoginHttpReturn mReturn = HttpJsonUtils2.doPostFormEncoded_Sync(LOGIN,
                        params, LoginHttpReturn.class);
                if (callback != null) {
                    callback.callback(mReturn);
                }
            }
        }.start();
    }

    /**
     * 发送邮箱验证码
     *
     * @param type
     * @param email
     * @param callback
     */
    public static void EmailVerficationCode(RequestType type, String email, DefaultCallbackInterface callback) {

        final List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("userEmail", email));

        String typeStr = "";
        switch (type) {
            case ChineseRegister:
                typeStr = "cn_zc";
                break;
            case ChineseRetrieve:
                typeStr = "cn_zh";
                break;
            case EnglishRegister:
                typeStr = "en_zc";
                break;
            case EnglishRetrieve:
                typeStr = "en_zh";
                break;
        }
        params.add(new BasicNameValuePair("reqType", typeStr));

        params.add(new BasicNameValuePair("appkey", APP_KEY));
        String timestamp = Calendar.getInstance().getTimeInMillis() / 1000 + "";
        params.add(new BasicNameValuePair("timestamp", timestamp));
        params.add(pair_secret);


        StringableHashMap map = new StringableHashMap();
        map.addIn(params);
        String sign = Sha1.encode(map.toString());
        params.add(new BasicNameValuePair("sign", sign));
        params.remove(pair_secret);

        new Thread() {
            @Override
            public void run() {
                LoginHttpReturn mReturn = HttpJsonUtils2.doGetHttpRequest_Sync(CHECK_EMAIL,
                        params, LoginHttpReturn.class);
                if (callback != null) {
                    callback.callback(mReturn);
                }
            }
        }.start();
    }

    /**
     * 发送短信验证码
     *
     * @param type
     * @param phone
     * @param callback
     */
    public static void PhoneVerficationCode(RequestType type, String phone, DefaultCallbackInterface callback) {

        final List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("phone", phone));
        String typeStr = "";
        switch (type) {
            case ChineseRegister:
                typeStr = "zc";
                break;
            case ChineseRetrieve:
                typeStr = "zh";
                break;
            case EnglishRegister:
                typeStr = "en_zc";
                break;
            case EnglishRetrieve:
                typeStr = "en_zh";
                break;
        }
        params.add(new BasicNameValuePair("reqType", typeStr));

        params.add(new BasicNameValuePair("appkey", APP_KEY));
        String timestamp = Calendar.getInstance().getTimeInMillis() / 1000 + "";
        params.add(new BasicNameValuePair("timestamp", timestamp));
        params.add(pair_secret);


        StringableHashMap map = new StringableHashMap();
        map.addIn(params);
        String sign = Sha1.encode(map.toString());
        params.add(new BasicNameValuePair("sign", sign));


        new Thread() {
            @Override
            public void run() {
                LoginHttpReturn mReturn = HttpJsonUtils2.doGetHttpRequest_Sync(CHECK_MESSAGE,
                        params, LoginHttpReturn.class);
                if (callback != null) {
                    callback.callback(mReturn);
                }
            }
        }.start();
    }

    /**
     *  注册
     * @param isEmailLogin
     * @param username
     * @param password
     * @param checkCode
     * @param callback
     */
    public static void Register(boolean isEmailLogin, String username, String password,
                                DefaultCallbackInterface callback) {

        final List<NameValuePair> params = new ArrayList<>();

        if (isEmailLogin) {
            params.add(new BasicNameValuePair("userEmail", username));
        } else {
            params.add(new BasicNameValuePair("phone", username));
        }
        params.add(new BasicNameValuePair("userpwd", MD5.getMd5_32(password)));

        params.add(new BasicNameValuePair("appkey", APP_KEY));
        String timestamp = Calendar.getInstance().getTimeInMillis() / 1000 + "";
        params.add(new BasicNameValuePair("timestamp", timestamp));
        params.add(pair_secret);


        StringableHashMap map = new StringableHashMap();
        map.addIn(params);
        String sign = Sha1.encode(map.toString());
        params.add(new BasicNameValuePair("sign", sign));

        new Thread() {
            @Override
            public void run() {
                LoginHttpReturn mReturn = HttpJsonUtils2.doPostFormEncoded_Sync(REGISTRATION,
                        params, LoginHttpReturn.class);
                if (callback != null) {
                    callback.callback(mReturn);
                }
            }
        }.start();

    }
    public static final String KEY_reqType = "reqType";
    public static void checkCode(boolean isEmailLogin, String username, String checkCode,
                                DefaultCallbackInterface callback) {

        final List<NameValuePair> params = new ArrayList<>();

        if (isEmailLogin) {
            params.add(new BasicNameValuePair("userEmail", username));
        } else {
            params.add(new BasicNameValuePair("phone", username));
        }

        params.add(new BasicNameValuePair("code", checkCode));

        params.add(new BasicNameValuePair("appkey", APP_KEY));
        String timestamp = Calendar.getInstance().getTimeInMillis() / 1000 + "";
        params.add(new BasicNameValuePair("timestamp", timestamp));
        params.add(pair_secret);


        StringableHashMap map = new StringableHashMap();
        map.addIn(params);
        String sign = Sha1.encode(map.toString());
        params.add(new BasicNameValuePair("sign", sign));

        new Thread() {
            @Override
            public void run() {
                LoginHttpReturn mReturn = HttpJsonUtils2.doGetHttpRequest_Sync(CheckCode,
                        params, LoginHttpReturn.class);
                if (callback != null) {
                    callback.callback(mReturn);
                }
            }
        }.start();

    }

    /**
     * 重置密码
     * @param isEmailLogin
     * @param username
     * @param password
     * @param checkCode
     * @param callback
     */
    public static void Retrieve(boolean isEmailLogin, String username, String password,
                                DefaultCallbackInterface callback) {

        final List<NameValuePair> params = new ArrayList<>();

        if (isEmailLogin) {
            params.add(new BasicNameValuePair("userEmail", username));
        } else {
            params.add(new BasicNameValuePair("phone", username));
        }
        params.add(new BasicNameValuePair("userpwd", MD5.getMd5_32(password)));

        params.add(new BasicNameValuePair("appkey", APP_KEY));
        String timestamp = Calendar.getInstance().getTimeInMillis() / 1000 + "";
        params.add(new BasicNameValuePair("timestamp", timestamp));
        params.add(pair_secret);

        StringableHashMap map = new StringableHashMap();
        map.addIn(params);
        String sign = Sha1.encode(map.toString());
        params.add(new BasicNameValuePair("sign", sign));

        new Thread() {
            @Override
            public void run() {
                LoginHttpReturn mReturn = HttpJsonUtils2.doPostFormEncoded_Sync(RESET_PASSWORD,
                        params, LoginHttpReturn.class);
                if (callback != null) {
                    callback.callback(mReturn);
                }
            }
        }.start();
    }

    public static enum RequestType {
        ChineseRegister,
        ChineseRetrieve,
        EnglishRegister,
        EnglishRetrieve
    }

    public static class StringableHashMap extends HashMap<String, String> {


        @Override
        public String toString() {

            StringBuffer buffer = new StringBuffer();

            // String current_key = null;
            ArrayList<String> list = new ArrayList<>();
            Iterator<String> iterator = super.keySet().iterator();
            HashMap<String, Object> unique_keep = new HashMap<>();


            while (iterator.hasNext()) {
                list.add(iterator.next());
            }

            for (int i = 0; i < list.size(); i++) {

                String temp = null;

                for (int j = 0; j < list.size(); j++) {

                    String current_key = list.get(j);

                    if (temp == null) {

                        if (unique_keep.containsKey(current_key)) {

                            continue;

                        } else {

                            temp = current_key;
                        }

                    } else if (!unique_keep.containsKey(current_key) &&
                            compare(current_key, temp) == LESS
                            ) {


                        temp = current_key;
                    }
                }

                unique_keep.put(temp, null);
                buffer.append(temp);
                buffer.append("=");
                buffer.append(super.get(temp));

                if (i + 1 < size()) {
                    buffer.append("&");
                }

            }

            Log.e("abc", buffer.toString());

            return buffer.toString();

        }

        public StringableHashMap addIn(List<NameValuePair> list) {

            for (NameValuePair valuePair : list) {

                put(valuePair.getName(), valuePair.getValue());

            }

            return this;
        }

        private static final int LESS = -1;
        private static final int BIG = 1;
        private static final int EQUAL = 0;

        private int compare(String str1, String str2) {
            //     int result = 0;
            for (int i = 0; i < Math.min(str1.length(), str2.length()); i++) {

                if (str1.toLowerCase().charAt(i) == str2.toLowerCase().charAt(i)) {


                } else {

                    if (str1.toLowerCase().charAt(i) < str2.toLowerCase().charAt(i)) {

                        return LESS;

                    } else {

                        return BIG;

                    }


                }

            }

            return EQUAL;
        }
    }

}
